<?php

namespace app\controller\admin\calendar;

use app\model\admin\calendar\CalendarModule;
use laytp\controller\Backend;
use laytp\library\CommonFun;
use think\facade\Db;

/**
 * Class Career
 * @package app\controller\admin\ah
 */
class Module extends Backend
{
    public $orderRule=['sort' => 'DESC','id'=>'ASC'];
    protected $model;
    protected $noNeedAuth = ['index', 'info'];
    public function initialize()
    {
        $this->model = new CalendarModule();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    //添加
    public function add()
    {
        if(!$this->request->param("game_id")){
            return $this->error("缺少游戏id");
        }
        $count = $this->model->where("relation_id",$this->request->param("game_id"))->where("system_id",$this->request->param("system_id"))->count();
        if($count>0){
            return $this->error('游戏中心id已存在系统中');
        }
        $gameId = $this->request->param("game_id");
        $post = CommonFun::filterPostData($this->request->post());
        try{
            $post['relation_id'] = $gameId;
            if ($this->model->create($post)) {
                $this->clearCache();
                return $this->success('添加成功', $post);
            } else {
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    //编辑
    public function edit()
    {
        $id   = $this->request->param('id');
        $info = $this->model->find($id);
        if (!$info) {
            return $this->error('ID参数错误');
        }
        $count = $this->model->where("id","<>",$this->request->param("id"))->where("relation_id",$info->relation_id)->where("system_id",$this->request->param("system_id"))->count();
        if($count>0){
            return $this->error('游戏中心id已存在系统中');
        }
        $post = CommonFun::filterPostData($this->request->post());
        IF(isset($post->icon)&&!empty($post->icon)){
            $post->icon = getRelativeUrl( $post->icon);
        }
        foreach ($post as $k => $v) {
            $info->$k = $v;
        }
        try {
            $updateRes = $info->save();
            if ($updateRes) {
                $this->clearCache();
                return $this->success('编辑成功');
            } else {
                return $this->error('编辑失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }


}